<template>
  <div class="program-question-page">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="search-input-group">
          <label class="search-label">题目名称</label>
          <a-input
            v-model:value="queryParam.title"
            placeholder="请输入要搜索的题目名称"
            class="search-input"
            @pressEnter="handleSearch"
          />
        </div>

        <div class="difficulty-group">
          <label class="search-label">难度标签</label>
          <div class="difficulty-tags">
            <a-tag
              v-for="option in difficultyOptions"
              :key="option.label"
              :color="option.selected ? 'blue' : 'default'"
              @click="toggleDifficulty(option)"
              class="difficulty-tag"
            >
              {{ option.label }}
            </a-tag>
          </div>
        </div>

        <a-button type="primary" @click="handleSearch" class="search-btn">
          <template #icon><search-outlined /></template>
          搜索
        </a-button>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="question-list">
      <a-table
        :columns="columns"
        :data-source="questionVOList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="question-table"
      >
        <!-- 题号列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <span class="question-id">{{ record.id }}</span>
          </template>

          <!-- 题目名称列 -->
          <template v-else-if="column.key === 'title'">
            <a @click="goToQuestion(record)" class="question-name-link">
              {{ record.title }}
            </a>
          </template>

          <!-- 标签列 -->
          <template v-else-if="column.key === 'tags'">
            <div class="question-tags">
              <a-tag v-for="tag in record.tags" :key="tag" :color="getKnowledgePointColor(tag)" size="small">
                {{ tag }}
              </a-tag>
            </div>
          </template>

          <!-- 通过率列 -->
          <template v-else-if="column.key === 'submitNum'">
            <div class="pass-rate-cell">
              <span class="rate-text">{{ passRate(record) * 100 + '%' }}</span>
              <div class="rate-bar">
                <div class="rate-fill" :style="{ width: passRate(record) * 100 + '%' }"></div>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <div class="pass-rate-cell">
              {{dayjs(record?.createTime).format('YYYY-MM-DD HH:mm')}}
            </div>
          </template>
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-button type="primary" size="small" @click="goToQuestion(record)" class="action-btn">
              做题
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { listQuestionVoByPage } from '@/api/questionController'
import dayjs from 'dayjs'
const router = useRouter()
// 表格列定义
const columns = [
  {
    title: '题号',
    dataIndex: 'id',
    key: 'id',
    width: 180,
    ellipsis: true,
  },
  {
    title: '题目名称',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
  },
  {
    title: '内容简介',
    dataIndex: 'content',
    key: 'content',
    width: 320,
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: 220,
  },
  {
    title: '提交人数',
    dataIndex: 'submitNum',
    key: 'submitNum',
    width: 160,
    sorter: (a: any, b: any) => a.passRatePercent - b.passRatePercent,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
    sorter: (a: any, b: any) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
  },
  {
    title: '',
    key: 'action',
    width: 100,
    fixed: 'right' as const,
  },
]
// 页面数据
const loading = ref(false)
const passRate = (record:API.QuestionVO):string=>{
  return (record?.acceptedNum/ record?.submitNum).toFixed(1) ?? 0
}
// 搜索表单
const total = ref(0)
const queryParam = reactive<API.QuestionQueryRequest>({
  title:'',
  tags:[]
})
const questionVOList = ref<API.QuestionVO[]>([])
const fetchData = async ()=>{
  const res = await listQuestionVoByPage({
    ...queryParam
  })
  if(res.data.data && res.data.code === 0){
    questionVOList.value = res.data.data.records ?? []
    total.value = Number(res.data.data.total)
  }else{
    message.error("获取数据失败" + res.data.msg)
  }
}
// 难度选项
const difficultyOptions = ref([
  { label: '全部', selected: true },
  { label: '简单', selected: false },
  { label: '中等', selected: false },
  { label: '困难', selected: false },
])
// 分页配置
const pagination = computed(() => {
  return {
    current: queryParam.current ?? 1, //有则按照传过来的，否则默认为1
    pageSize: queryParam.pageSize ?? 10, //默认为 10
    total: Number(total.value) ?? 0, //默认为 0
    showSizeChanger: true,
    showTotal: (total :number) => `共${total}条数据`,
    size: 'small' as const,
    pageSizeOptions: ['10', '20', '30', '50'],
  }
})
// 方法
const toggleDifficulty = (option: any) => {
  if (option.label === '全部') {
    difficultyOptions.value.forEach((opt) => (opt.selected = opt.label === '全部'))
  } else {
    option.selected = !option.selected
    const allOption = difficultyOptions.value.find((opt) => opt.label === '全部')
    if (allOption) allOption.selected = false
  }
}

const handleSearch = async () => {
  loading.value = true
  // 获取选中的难度
  const selectedDifficulties = difficultyOptions.value
    .filter((opt) => opt.selected && opt.label !== '全部')
    .map((opt) => opt.label) //数组
  queryParam.tags = selectedDifficulties
  await fetchData()
  loading.value = false
}

const getTagColor = (tag: string) => {
  switch (tag) {
    case '简单':
      return 'green'
    case '中等':
      return 'orange'
    case '困难':
      return 'red'
    case '入门':
      return 'blue'
    case '图论':
      return 'purple'
    case '树':
      return 'cyan'
    case '堆':
      return 'geekblue'
    case '链表':
      return 'magenta'
    case '字符串':
      return 'volcano'
    case '哈希':
      return 'gold'
    case '递归':
      return 'lime'
    default:
      return 'default'
  }
}

const goToQuestion = (question: any) => {
  // 跳转到题目详情页面
  router.push(`/student/practice_program/${question.id}`)
}

const handleTableChange = (paginationInfo: any) => {
  console.log(paginationInfo)
  // 处理分页变化
  if (paginationInfo) {
    queryParam.current= paginationInfo.current
    fetchData()
  }
}

// 知识点颜色映射（动态生成）
const knowledgePointColors = [
  'magenta',
  'red',
  'volcano',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
  'pink',
]

const getKnowledgePointColor = (knowledgePoint: string) => {
  if (!knowledgePoint) return 'default'

  // 使用字符串哈希生成稳定的颜色索引
  let hash = 0
  for (let i = 0; i < knowledgePoint.length; i++) {
    const char = knowledgePoint.charCodeAt(i)
    hash = (hash << 5) - hash + char
    hash = hash & hash // 转换为32位整数
  }

  // 确保索引为正数并在颜色数组范围内
  const colorIndex = Math.abs(hash) % knowledgePointColors.length
  return knowledgePointColors[colorIndex]
}

onMounted(() => {
  // 页面初始化
  fetchData()
})
</script>

<style>
/* 全局样式优化 - 智能滚动条控制 */
.ant-layout-content {
  padding: 0 !important;
  margin-bottom: 0 !important;
}
</style>

<style scoped>
.program-question-page {
  max-width: 1500px; /* 限制最大宽度 */
  width: 100%;
  min-height: calc(100vh - 85px - 48px); /* 最小高度，允许内容超出时自动扩展 */
  margin: 0 auto; /* 水平居中 */
  padding: 16px 32px; /* 增加左右padding */
  background: #f5f5f5;
  overflow: visible; /* 允许内容自然展开 */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 搜索区域 */
.search-section {
  margin-top: 15px;
  background: white;
  border-radius: 12px 12px 0 0;
  padding: 20px 24px;
  margin-bottom: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e8e8e8;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
  box-sizing: border-box;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.search-input-group,
.difficulty-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-label {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  white-space: nowrap;
  min-width: 70px;
}

.search-input {
  width: 320px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: all 0.2s ease;
  height: 40px;
  font-size: 14px;
}

.search-input:hover {
  border-color: #40a9ff;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
}

.search-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.difficulty-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.difficulty-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 16px;
  padding: 8px 16px;
  font-size: 13px;
  font-weight: 500;
  border: 1px solid transparent;
}

.difficulty-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-btn {
  border-radius: 6px;
  height: 40px;
  padding: 0 20px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.2s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.3);
}

/* 题目列表 */
.question-list {
  background: white;
  border-radius: 0 0 12px 12px;
  padding: 20px 24px 24px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e8e8e8;
  border-top: none;
  flex: 1;
  overflow: visible; /* 允许内容自然展开 */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 表格样式 */
.question-table {
  flex: 1;
  overflow: visible; /* 允许表格自然展开 */
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.question-table :deep(.ant-table) {
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.question-table :deep(.ant-table-container) {
  overflow: visible; /* 让表格内容自然展开 */
}

.question-table :deep(.ant-table-content) {
  overflow: visible; /* 表格内容自然展开 */
}

.question-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  font-weight: 600;
  color: #262626;
  padding: 16px 12px;
  font-size: 14px;
  height: 56px;
}

.question-table :deep(.ant-table-tbody > tr > td) {
  padding: 16px 12px;
  border-bottom: 1px solid #f5f5f5;
  font-size: 14px;
  height: 64px;
}

.question-table :deep(.ant-table-tbody > tr:hover > td) {
  background: #f8f9fa;
}

.question-table :deep(.ant-table-tbody > tr:last-child > td) {
  border-bottom: none;
}

/* 分页样式 */
.question-table :deep(.ant-pagination) {
  margin-top: 20px;
  text-align: center; /* 居中显示 */
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
}

.question-table :deep(.ant-pagination-item) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  transition: all 0.2s ease;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin: 0 4px; /* 左右间距 */
}

.question-table :deep(.ant-pagination-item:hover) {
  border-color: #1890ff;
  color: #1890ff;
}

.question-table :deep(.ant-pagination-item-active) {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
  font-weight: 500;
}

.question-table :deep(.ant-pagination-prev),
.question-table :deep(.ant-pagination-next) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  transition: all 0.2s ease;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin: 0 4px; /* 左右间距 */
}

.question-table :deep(.ant-pagination-prev:hover),
.question-table :deep(.ant-pagination-next:hover) {
  border-color: #1890ff;
  color: #1890ff;
}

.question-table :deep(.ant-pagination-total-text) {
  color: #666;
  font-size: 14px;
  margin-right: 20px;
}

.question-table :deep(.ant-pagination-options) {
  margin-left: 20px;
  display: flex;
  align-items: center;
  gap: 12px; /* 选项之间的间距 */
}

.question-table :deep(.ant-pagination-options-size-changer) {
  margin-right: 0;
}

.question-table :deep(.ant-pagination-options-quick-jumper) {
  margin-left: 0;
}

/* 分页跳转输入框样式 */
.question-table :deep(.ant-pagination-options-quick-jumper input) {
  width: 50px;
  margin: 0 8px;
  text-align: center;
}

/* 表格单元格样式 */
.question-id {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 13px;
  color: #666;
  word-break: break-all;
  background: #f8f8f8;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.question-name-link {
  font-weight: 500;
  color: #262626;
  cursor: pointer;
  transition: color 0.3s ease;
  line-height: 1.4;
  text-decoration: none;
}

.question-name-link:hover {
  color: #1890ff;
}

.question-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.pass-rate-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.rate-text {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.rate-bar {
  width: 100px;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.rate-fill {
  height: 100%;
  background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.action-btn {
  border-radius: 4px;
  font-size: 13px;
  height: 32px;
  padding: 0 16px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 1600px) {
  .program-question-page {
    max-width: 1000px;
    padding: 14px 28px;
    min-height: calc(100vh - 85px - 48px);
  }
}

@media (max-width: 1200px) {
  .program-question-page {
    max-width: 900px;
    padding: 12px 24px;
    min-height: calc(100vh - 85px - 48px);
  }

  .search-section,
  .question-list {
    padding: 16px;
  }
}

@media (max-width: 992px) {
  .program-question-page {
    max-width: 100%;
    padding: 10px 20px;
    min-height: calc(100vh - 85px - 48px);
  }

  .search-section {
    padding: 16px 20px;
  }

  .question-list {
    padding: 16px 20px 20px 20px;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .search-input-group,
  .difficulty-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .search-input {
    width: 100%;
  }

  .search-label {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .program-question-page {
    padding: 8px 16px;
    min-height: calc(100vh - 85px - 48px);
  }

  .search-section {
    padding: 16px;
    border-radius: 12px 12px 0 0;
  }

  .question-list {
    padding: 16px 16px 20px 16px;
    border-radius: 0 0 12px 12px;
  }

  .search-form {
    gap: 12px;
  }

  .difficulty-tags {
    gap: 6px;
  }

  /* 移动端表格滚动 */
  .question-table :deep(.ant-table-content) {
    overflow-x: auto;
  }

  .question-table :deep(.ant-table) {
    min-width: 600px;
  }

  .question-tags {
    justify-content: flex-start;
  }

  .pass-rate-cell {
    flex-direction: row;
    align-items: center;
    gap: 12px;
  }

  .rate-bar {
    width: 60px;
  }
}

@media (max-width: 480px) {
  .program-question-page {
    padding: 6px 12px;
    min-height: calc(100vh - 85px - 48px);
  }

  .search-section {
    padding: 12px;
    border-radius: 12px 12px 0 0;
  }

  .question-list {
    padding: 12px 12px 16px 12px;
    border-radius: 0 0 12px 12px;
  }

  .question-table :deep(.ant-table) {
    min-width: 500px;
  }

  .pass-rate-cell {
    gap: 6px;
  }

  .rate-bar {
    width: 40px;
  }

  /* 移动端分页样式优化 */
  .question-table :deep(.ant-pagination) {
    text-align: center;
    padding: 12px 0;
  }

  .question-table :deep(.ant-pagination-item),
  .question-table :deep(.ant-pagination-prev),
  .question-table :deep(.ant-pagination-next) {
    margin: 0 2px;
    min-width: 28px;
    height: 28px;
    font-size: 12px;
  }

  .question-table :deep(.ant-pagination-options) {
    margin-left: 12px;
    gap: 8px;
  }

  .question-table :deep(.ant-pagination-total-text) {
    margin-right: 12px;
    font-size: 12px;
  }
}
</style>
